package com.financing.wap.web.controller.api;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.CommonConstantUtil.CommonStatus;
import com.financing.wap.common.ResultMap;
import com.financing.wap.dto.DstMemberInfoDTO;
import com.financing.wap.dto.DstMemberSendLogDTO;
import com.financing.wap.dto.DstUserInfoDTO;
import com.financing.wap.dto.DstUserInfoExpandDTO;
import com.financing.wap.dto.DstUserIntegralFlowDTO;
import com.financing.wap.dto.DstVirtualGoodsDTO;
import com.financing.wap.service.ICommonDstService;
import com.financing.wap.service.IDstIntegralRuleService;
import com.financing.wap.service.IDstMemberInfoService;
import com.financing.wap.service.IDstMemberSendLogService;
import com.financing.wap.service.IDstUserInfoExpandService;
import com.financing.wap.service.IDstUserInfoService;
import com.financing.wap.service.IDstUserIntegralFlowService;
import com.financing.wap.service.IDstVirtualGoodsService;
import com.financing.wap.service.weixin.service.WeixinService;
import com.financing.wap.util.AliyunOssUtil;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.DstUserGrowthModeVO;
import com.financing.wap.web.controller.BaseController;

@Controller("dstMemberInfoController")
@RequestMapping("/api/dstMemberInfo")
public class DstMemberInfoController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private IDstMemberInfoService dstMemberInfoService;
	

	@Autowired
	private WeixinService weixinJincsServiceImpl;

	@Autowired
	private IDstUserInfoService dstUserInfoService;

	@Autowired
	private IDstUserInfoExpandService dstUserInfoExpandService;

	@Autowired
	private IDstUserIntegralFlowService dstUserIntegralFlowService;

	@Autowired
	private ICommonDstService commonDstService;

	@Autowired
	private IDstVirtualGoodsService dstVirtualGoodsService;
	
	@Autowired
	private IDstIntegralRuleService dstIntegralRuleService;

	// 保存文件到本地目录
	private static String ossUserCardPath = PropertiesUtils.getValue("ossUserCardPath");
	
	//邀请关注的背景图
	String InviteAttentionImage =PropertiesUtils.getValue("ossBaseDir")+"/mark2.jpg";

    @Autowired
    private IDstMemberSendLogService dstMemberSendLogService;
	
	/***
	 * 用户基本会员信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/detailDstMemberInfo")
	@ResponseBody
	public ResultMap detail(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query detail dstMemberInfo  begin .......");
			String openid = request.getParameter("openid");
			if(StringUtil.isNullOrEmptyStr(openid)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			//用户会员信息
			DstMemberInfoDTO dstMemberInfo=new DstMemberInfoDTO();
			dstMemberInfo.setUserOpenid(openid);
			DstMemberInfoDTO dto = dstMemberInfoService.queryListGetFirst(dstMemberInfo);
			//用户基础微信信息
			DstUserInfoDTO dstUserInfo = new DstUserInfoDTO();
			dstUserInfo.setUserWechatOpenid(openid);
			dstUserInfo
					.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			DstUserInfoDTO userinfo = dstUserInfoService
					.queryListGetFirst(dstUserInfo);
			//用户扩展信息
			DstUserInfoExpandDTO dstUserInfoExpand=new DstUserInfoExpandDTO();
			dstUserInfoExpand.setUserOpenid(openid);
			DstUserInfoExpandDTO expand = dstUserInfoExpandService.queryListGetFirst(dstUserInfoExpand);
			
			result.setAttribute("userinfo",userinfo);
			result.setAttribute("dto",dto);
			result.setAttribute("userexpan",expand);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query detail dstMemberInfo  end .......");
		}catch(Exception e){
			log.error("query detail dstMemberInfo error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	
	/***
	 *获取用户带参数二维码
	 * @param request
	 * @return
	 */
	@RequestMapping("/qrCodePicture")
	@ResponseBody
	public ResultMap qrCodePicture(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info(" qrCodePicture  begin .......");
			String openid = request.getParameter("openid");
			if(StringUtil.isNullOrEmptyStr(openid)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}

			DstUserInfoDTO dstUserInfo = new DstUserInfoDTO();
			dstUserInfo.setUserWechatOpenid(openid);
			dstUserInfo.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			DstUserInfoDTO userinfo = dstUserInfoService
					.queryListGetFirst(dstUserInfo);
			if(userinfo.getId()==null){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
		     //目录
	        StringBuffer userShare = new StringBuffer();
	        userShare.append(ossUserCardPath)
	                .append("/").append("userShareRes").append("/")
	                .append(DateUtil.formatDate(userinfo.getCreateDate(), "yyyyMMdd")).append("/")
	                .append(openid).append("_").append(".jpg");
	        
	        result.setAttribute("imageUrl",CommonConstantUtil.OSS_PATH+userShare.toString());
	        
	        //如果存在分享海报 直接返回
			if(AliyunOssUtil.doesObjectExist(userShare.toString())){
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setStatus(ResultMap.STATUS.SUCCESS);
				return result;
			}
			
		     //目录
	        StringBuffer fileFull = new StringBuffer();
	        fileFull.append(ossUserCardPath)
	                .append("/").append("userShareRegister").append("/")
	                .append(DateUtil.formatDate(userinfo.getCreateDate(), "yyyyMMdd")).append("/")
	                .append(openid).append("_").append(".jpg");
	        
			if(!AliyunOssUtil.doesObjectExist(fileFull.toString())){
				//生成永久 
				try {
					weixinJincsServiceImpl.qrCodePicture(userinfo.getUserWechatOpenid(),fileFull.toString());
				} catch (Exception e) {
					logger.info("weixinJincsServiceImpl.qrCodePicture  end .......",e);
				}
			}
			//生成永久图片
			String userWchateImage = userinfo.getUserWechatImage();
			String headTemp=ossUserCardPath+"/tempHeadImage2/"+DateUtil.getDate("yyyyMMdd")+"/"+userinfo.getUserWechatOpenid()+".jpg";
			String tempPath="/disk/upload/watertemp/"+userinfo.getUserWechatOpenid()+".jpg";
			AliyunOssUtil.markRegister(InviteAttentionImage, fileFull.toString(), tempPath, headTemp, userWchateImage, userShare.toString());
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("qrCodePicture  end .......");
		}catch(Exception e){
			log.error("qrCodePicture error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/***
	 * 领取积分
	 * @param request
	 * @return
	 */
	@RequestMapping("/receive")
	@ResponseBody
	public ResultMap receive(HttpServletRequest request){
		ResultMap result = new ResultMap();

		try{
			logger.info(" receive  begin .......");
			String openid = request.getParameter("openid");
			String type = request.getParameter("type");
			if(StringUtil.isNullOrEmptyStr(openid,type)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}

			DstUserIntegralFlowDTO dstUserIntegralFlow = new DstUserIntegralFlowDTO();
			dstUserIntegralFlow.setUserOpenid(openid);
			dstUserIntegralFlow.setType(type);
			dstUserIntegralFlow = dstUserIntegralFlowService.queryListGetFirst(dstUserIntegralFlow);

            if("2".equals(dstUserIntegralFlow.getIntegralStatus())){
                logger.info("has receive!");
                result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
                result.setStatus(ResultMap.STATUS.SUCCESS);
                return result;
            }

			if(dstUserIntegralFlow.getId() == null){
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}

			dstUserIntegralFlow.setIntegralStatus("2");
			dstUserIntegralFlow.setUpdateDate(new Date());
			dstUserIntegralFlowService.update(dstUserIntegralFlow);

            //更新累计积分
            DstMemberInfoDTO dstMemberInfo = new DstMemberInfoDTO();
            dstMemberInfo.setUserOpenid(openid);
            dstMemberInfo = dstMemberInfoService.queryListGetFirst(dstMemberInfo);
            dstMemberInfo.setMemberScore(dstMemberInfo.getMemberScore() == null?0:dstMemberInfo.getMemberScore()  + dstUserIntegralFlow.getGrade());
            dstMemberInfoService.update(dstMemberInfo);

			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			logger.info(" receive  end .......");

		}catch(Exception e){
			log.error("receive error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/***
	 * 用户成长列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/growthMode")
	@ResponseBody
	public synchronized ResultMap growthMode(HttpServletRequest request){
		ResultMap result = new ResultMap();

		try{
			logger.info(" growthMode  begin .......");
			String openid = request.getParameter("openid");
			if(StringUtil.isNullOrEmptyStr(openid)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}

			DstUserInfoDTO dstUserInfo = new DstUserInfoDTO();
			dstUserInfo.setUserWechatOpenid(openid);
			dstUserInfo.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			DstUserInfoDTO userinfo = dstUserInfoService
					.queryListGetFirst(dstUserInfo);
			if(userinfo.getId()==null){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			//积分规则
			dstIntegralRuleService.execute(openid,"userCard");

			Map buyMap = new HashMap();
			buyMap.put("speed", 0);
			buyMap.put("status","0");
			buyMap.put("grade",0);

			List<DstUserGrowthModeVO> list = commonDstService.growthMode(openid);
			for(DstUserGrowthModeVO bean:list){
				if("userCard".equals(bean.getBusinessType())){
					result.setAttribute("userCard",setUserCard(openid,bean));
				}
				if("shareArticle".equals(bean.getBusinessType())){
					result.setAttribute("shareArticle",setShareArticle(bean));
				}
				if("visitArticlePeople".equals(bean.getBusinessType())){
					result.setAttribute("visitArticlePeople",setVisitArticlePeople(bean,openid));
				}
				if("inviteOpenMembers".equals(bean.getBusinessType())){
					result.setAttribute("inviteOpenMembers",setInviteOpenMembers(bean));
				}
				if("buyYear".equals(bean.getBusinessType()) ||
						"buyQuarter".equals(bean.getBusinessType()) ||
						"buyHalfYear".equals(bean.getBusinessType()) ){
					setBuy(bean,buyMap);
				}

			}

			result.setAttribute("buyMap",buyMap);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			logger.info(" growthMode  end .......");

		}catch(Exception e){
			log.error("growthMode error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/***
	 * 积分兑换
	 * @param request
	 * @return
	 */
	@RequestMapping("/exchange")
	@ResponseBody
	public ResultMap exchange(HttpServletRequest request){
		ResultMap result = new ResultMap();

		try{
			logger.info(" exchange  begin .......");

			String openid = request.getParameter("openid");
			String id = request.getParameter("id");
			String phone = request.getParameter("phone");
            String remark = request.getParameter("remark");

			if(StringUtil.isNullOrEmptyStr(openid,id)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}

            DstVirtualGoodsDTO dstVirtualGoods = dstVirtualGoodsService.loadById(Integer.valueOf(id));

			if(dstVirtualGoods.getId() == null){
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setStatus(ResultMap.STATUS.FAILE);//商品不存在
				return result;
			}


			DstMemberInfoDTO dstMemberInfo = new DstMemberInfoDTO();
			dstMemberInfo.setUserOpenid(openid);
			dstMemberInfo.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			dstMemberInfo = dstMemberInfoService.queryListGetFirst(dstMemberInfo);

			if(dstMemberInfo.getId() == null){
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);//会员不存在
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}

			Integer available =  ((dstMemberInfo.getMemberScore()==null)?0:dstMemberInfo.getMemberScore()) - ((dstMemberInfo.getMemberUseScore()==null)?0:dstMemberInfo.getMemberUseScore());
			if(available < dstVirtualGoods.getGoodsAmount().intValue()){
				result.setStatusCode(ResultMap.INTEGRAL_DEFICIENCY);//积分不足
				result.setStatus(ResultMap.STATUS.SUCCESS);
				return result;
			}

            //业务逻辑
            Map<String,String> map = new HashMap<String, String>();
            map.put("phone",phone);
            map.put("remark",remark);
            dstMemberInfoService.exchange(dstMemberInfo,dstVirtualGoods,map);


			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			logger.info(" exchange  end .......");

		}catch(Exception e){
			log.error("exchange error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;
	}

	/***
	 * 会员开通记录
	 * @param request
	 * @return
	 */
	@RequestMapping("/memberlog")
	@ResponseBody
	public ResultMap memberlog(HttpServletRequest request){
		ResultMap result = new ResultMap();

		try{
			logger.info(" memberlog  begin .......");

			String openid = request.getParameter("openid");
			if(StringUtil.isNullOrEmptyStr(openid)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			 //会员开通记录
            DstMemberSendLogDTO dstMemberSendLog = new DstMemberSendLogDTO();
            dstMemberSendLog.setUserOpenid(openid);
            List<DstMemberSendLogDTO> memberLogList = dstMemberSendLogService.queryList(dstMemberSendLog);
            result.setAttribute("list",memberLogList);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			logger.info(" memberlog  end .......");

		}catch(Exception e){
			log.error("memberlog error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;
	}
	
	public void setBuy(DstUserGrowthModeVO bean, Map buyMap) {
		if(StringUtils.isBlank(bean.getType())){
			return;
		}
		buyMap.put("speed",(Integer)buyMap.get("speed")+bean.getCount());
		buyMap.put("grade",(Integer)buyMap.get("grade")+bean.getSumGrade());

	}

	public Map setUserCard(String openid,DstUserGrowthModeVO bean) throws SQLException {

		Map map = new HashMap();

		if(StringUtils.isNotBlank(bean.getType())){
			map.put("speed",100);
			map.put("grade",bean.getSumGrade());
			if("1".equals(bean.getIntegralStatus())) {
				map.put("status", "1");
			}else{
				map.put("status", "2");
			}
			return map;
		}


		DstUserInfoExpandDTO addInfo=new DstUserInfoExpandDTO();
		addInfo.setUserOpenid(openid);
		DstUserInfoExpandDTO userInfoExpand = dstUserInfoExpandService.queryListGetFirst(addInfo);


		int speed = 0;
		//姓名、电话、二维吗各占进度20%，公司、邮箱、职务、地址各占10%合计100%
		//if(StringUtils.isNotBlank(userInfoExpand.getUserName()) ){
			speed = speed+20;// 姓名默认 有
		//}
		if(StringUtils.isNotBlank(userInfoExpand.getUserPhone()) ){
			speed = speed+20;
		}
		if(StringUtils.isNotBlank(userInfoExpand.getUserCardImg()) ){
			speed = speed+20;
		}

		if(StringUtils.isNotBlank(userInfoExpand.getUserPosition()) ){
			speed = speed+10;
		}
		if(StringUtils.isNotBlank(userInfoExpand.getUserEmail()) ){
			speed = speed+10;
		}
		if(StringUtils.isNotBlank(userInfoExpand.getUserCompany()) ){
			speed = speed+10;
		}
		if(StringUtils.isNotBlank(userInfoExpand.getUserAddress()) ){
			speed = speed+10;
		}
		map.put("speed",speed);
		map.put("grade",0);
		map.put("status","0");
		return map;

	}
	public Map setShareArticle(DstUserGrowthModeVO bean) throws SQLException {

		Map map = new HashMap();

		if(StringUtils.isNotBlank(bean.getType())) {
			map.put("speed", bean.getCountDate()*10);
			map.put("grade", bean.getSumDateGrade());
			map.put("status", bean.getCountDate()>=10?"2":"0");
		}else{
			map.put("speed", 0);
			map.put("grade", 0);
			map.put("status", "0");
		}

		return map;
	}
	public Map setVisitArticlePeople(DstUserGrowthModeVO bean,String openId) throws SQLException {

		Map map = new HashMap();

		//查询拜访记录
		Map<String,String> mapCount = new HashMap<String,String>();
		mapCount.put("visitDate",DateUtil.getDate("yyyy-MM-dd"));
		mapCount.put("openid",openId);
		int count =  commonDstService.visitExecuteUpperLimit(mapCount);
        int  ruleFrequencyType = bean.getRuleFrequencyType() == null ?100 : bean.getRuleFrequencyType()*10;
        if(count >= ruleFrequencyType){
            count = ruleFrequencyType;
        }

		if(StringUtils.isNotBlank(bean.getType())) {
			map.put("speed", count);
			map.put("grade", bean.getSumDateGrade());
			map.put("status", bean.getCount()>=10?"2":"0");
		}else{
			map.put("speed", count);
			map.put("grade", 0);
			map.put("status", "0");
		}

		return map;
	}
	public Map setInviteOpenMembers(DstUserGrowthModeVO bean) throws SQLException {

		Map map = new HashMap();
		if(StringUtils.isNotBlank(bean.getType())) {
			map.put("speed", bean.getCount());
			map.put("grade", bean.getSumDateGrade());
			map.put("status", "0");
		}else{
			map.put("speed", 0);
			map.put("grade", 0);
			map.put("status", "0");
		}
		return map;
	}
}
